package com.yami.shop.app.controller;

import cn.hutool.core.date.DateUtil;
import com.yami.shop.app.dto.*;
import com.yami.shop.app.utils.HttpResult;
import com.yami.shop.common.util.Json;
import com.yami.shop.sys.model.SysConfig;
import com.yami.shop.sys.service.SysConfigService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

@RestController
@RequestMapping("/app/officialAccount")
public class OfficialAccountController {

    private static final String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx53753d880795f1ff&secret=3f14a33384b365796a5a8edc6dfc7b5d";

    public static final String createCardUrl = "https://api.weixin.qq.com/card/create?access_token=";

    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 验证服务器信息
     */
//    @GetMapping("/testServer")
//    public String testServer( TestServerParam testServerParam){
//        String  nonce = testServerParam.getNonce();
//        String signature = testServerParam.getSignature();
//        String timestamp = testServerParam.getTimestamp();
//        String echostr = testServerParam.getEchostr();
//        if (WechatUtil.checkSignature(signature, timestamp, nonce)) {
//            //返回随机数
//            System.out.print("随机数"+echostr);
//            return echostr;
//        }
//        return null;
//    }

    /**
     * 获取token,与当前时间比对。
     */
    public  String getToken(){
        //获取数据库中的token值
        SysConfig sysConfig = sysConfigService.getSysConfigByValue("offical_token", DateUtil.offsetHour(new Date(),2));
        if(sysConfig!=null){
            String token = sysConfigService.getValue("offical_token");
            return token;
        }else{
            //重新申请token,保存进入数据库
            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            String result = null;
            try {
                HttpResponse response = defaultHttpClient.execute(httpGet);
                HttpEntity entity = response.getEntity();
                if(entity != null){
                     result = EntityUtils.toString(entity, "UTF-8");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取token地址值
            SysConfig newSysConfig = sysConfigService.queryByKey("offical_token");
            JSONObject jsonObj = new JSONObject(result);
            String accessToken =  jsonObj.getString("access_token");
            newSysConfig.setParamValue(accessToken);
            newSysConfig.setCreateTime(new Date());
            sysConfigService.saveOrUpdate(newSysConfig);
            return accessToken;
        }

    }


    /**
     *
     */
    @PostMapping("/createCard")
    @ResponseBody
    public HttpResult createCard() throws IOException {
        StringBuffer buffer = new StringBuffer(createCardUrl);
        buffer.append(getToken());
        Card card = new Card();
        card.setCard_type("MEMBER_CARD");
        BaseInfo baseInfo = new BaseInfo();
        MemberCard memberCard = new MemberCard();
        HashMap map = new HashMap();
        baseInfo.setLogo_url("http://mmbiz.qpic.cn/mmbiz_png/tXyhsdIXQRRV2Q85dHuB9yTiaG3C4dQaaFuk6e3ekZykJQ8eJVnyKDZqBOhtFKR21o50Hbavvoia67LLPzxic1N0w/0");
        baseInfo.setBrand_name("小二啷当");
        baseInfo.setCode_type("CODE_TYPE_ONLY_QRCODE");
        baseInfo.setTitle("会员卡");
        baseInfo.setColor("Color010");
        baseInfo.setNotice("请在付款的时候出示会员卡");
        baseInfo.setService_phone("18721961968");
        baseInfo.setDescription("不可借给他人使用!");
        DateInfo dateInfo = new DateInfo();
        dateInfo.setType("DATE_TYPE_PERMANENT");
        baseInfo.setDate_info(dateInfo);
        Sku skuDto = new Sku();
        skuDto.setQuantity(5000);
        baseInfo.setSku(skuDto);
        baseInfo.setGet_limit(1);
        baseInfo.setUse_custom_code(true);
        baseInfo.setCan_give_friend(false);
       // baseInfo.setQuantity(100);
        card.setMember_card(memberCard);
        memberCard.setBackground_pic_url("http://mmbiz.qpic.cn/mmbiz_png/tXyhsdIXQRRV2Q85dHuB9yTiaG3C4dQaaAgldrjNDUkHvj2kuO18rFicbiaTljcr5pgV3wxCSb2Of69IdIawTDrRQ/0");
        memberCard.setBase_info(baseInfo);
        memberCard.setSupply_balance(true);
        memberCard.setSupply_balance(true);
        memberCard.setPrerogative("test_prerogative");
        memberCard.setAuto_activate(false);
        memberCard.setActivate_url("https://www.xiaoerlangdang.com");
        String result = null;

        WxCard wxCard = new WxCard();
        wxCard.setCard(card);


        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(buffer.toString());
        System.out.print("输出的json格式为"+Json.toJsonString(wxCard));
        StringEntity se = new StringEntity(Json.toJsonString(wxCard), "UTF-8");
        se.setContentType("application/json");
        httpPost.setEntity(se);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String resStr = null;
        if (entity1 != null) {
            resStr = EntityUtils.toString(entity1, "UTF-8");
        }
        httpClient.close();
        response.close();

        return  HttpResult.success();

    }


    @GetMapping("/testServer")
    public String testServer( TestServerParam testServerParam){
       if(testServerParam!=null){
           //获取事件类型
           String event = testServerParam.getEvent();
           if(null!=event&&!"".equals(event)){
               if("card_pass_check".equals(event)){
                   cardPassCheck(testServerParam);
               }
               if("card_not_pass_check".equals(event)){
                   cardPassCheck(testServerParam);
               }

           }
       }
        return null;
    }

    public HttpResult cardPassCheck(TestServerParam testServerParam){
        System.out.println("接收到的信息为"+testServerParam.toString());
        return HttpResult.success();
    }



}
